package porter

import (
	"context"
	"github.com/tidwall/gjson"
	"shop/src/model"
	"shop/src/open/akc"
	"time"
)

var akcClient = akc.NewClient()

type akcTradeFetcher struct {
	store *model.Store
}

func (f *akcTradeFetcher) fetch(startTime time.Time, endTime time.Time, pageNo int, parameter any, hasTotal bool) (any, error) {
	result, err := akcClient.Execute(context.Background(), "aikucun.delivery.trade.order.search", akc.Parameters{
		"startDate":  startTime.UnixMilli(),
		"endDate":    endTime.UnixMilli(),
		"status":     parameter.(string),
		"queryType":  1,
		"pageNo":     pageNo,
		"pageSize":   f.pageSize(),
		"useHasNext": !hasTotal,
	})
	if err != nil {
		return nil, err
	}
	return result.Get("data"), nil
}

func (f *akcTradeFetcher) hasTotal() bool {
	return false
}

func (f *akcTradeFetcher) count(resp any) int {
	result := resp.(gjson.Result)
	return int(result.Get("totalRecord").Int())
}

func (f *akcTradeFetcher) buildDocument(resp any) []model.Document {
	result := resp.(gjson.Result)
	list := result.Get("orderList").Array()
	documents := make([]model.Document, len(list))
	for _, it := range list {
		var document model.Document
		document.Sn = it.Get("adOrderId").String()
		document.Doc = it.String()
		documents = append(documents, document)
	}
	return documents
}

func (f *akcTradeFetcher) pageSize() int {
	return 100
}

func (f *akcTradeFetcher) startPage() int {
	return 1
}

func (f *akcTradeFetcher) parameters() []any {
	return []any{4}
}

type akcRefundFetcher struct {
	store *model.Store
}

func (f *akcRefundFetcher) fetch(startTime time.Time, endTime time.Time, pageNo int, _ any, _ bool) (any, error) {
	result, err := akcClient.Execute(context.Background(), "aikucun.aftersale.order.list", akc.Parameters{
		"startModified": startTime.UnixMilli(),
		"endModified":   endTime.UnixMilli(),
		"pageNum":       pageNo,
		"pageSize":      f.pageSize(),
	})
	if err != nil {
		return nil, err
	}
	return result.Get("data"), nil
}

func (f *akcRefundFetcher) hasTotal() bool {
	return false
}

func (f *akcRefundFetcher) count(resp any) int {
	result := resp.(gjson.Result)
	return int(result.Get("totalCount").Int())
}

func (f *akcRefundFetcher) buildDocument(resp any) []model.Document {
	result := resp.(gjson.Result)
	list := result.Get("result").Array()
	documents := make([]model.Document, len(list))
	for _, it := range list {
		var document model.Document
		document.Sn = it.Get("adId").String()
		document.Rsn = it.Get("asServiceNum").String()
		document.Doc = it.String()
		documents = append(documents, document)
	}
	return documents
}

func (f *akcRefundFetcher) pageSize() int {
	return 100
}

func (f *akcRefundFetcher) startPage() int {
	return 1
}

func (f *akcRefundFetcher) parameters() []any {
	return []any{}
}
